from flask import render_template, Response, redirect, url_for, jsonify, request
from flask_login import current_user, login_required
from . import gesture
from gesture_recognition import generate_frames, get_gesture, get_contents, receive_content, input_contents
from models import GestureRecord, User, db
from utils.cache import get_cached_gesture_contents
import os
from werkzeug.utils import secure_filename
import uuid

# 配置视频上传
UPLOAD_FOLDER = 'static/videos'
ALLOWED_EXTENSIONS = {'mp4', 'avi', 'mov', 'wmv'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@gesture.route('/recognition')
@login_required
def recognition():
    if not current_user.is_authenticated:
        return redirect(url_for('auth.login_route'))
    if current_user.role == 'admin':
        return redirect(url_for('user.user_management'))
    return render_template('recognition.html')

@gesture.route('/video_feed')
@login_required
def video_feed():
    return Response(generate_frames(),
                   mimetype='multipart/x-mixed-replace; boundary=frame')

@gesture.route('/get_gesture')
@login_required
def get_gesture_route():
    return get_gesture()

@gesture.route('/get_contents')
@login_required
def get_contents_route():
    # 尝试从缓存获取手势指令内容
    cached_contents = get_cached_gesture_contents()
    if cached_contents:
        return jsonify(cached_contents)
    return get_contents()

@gesture.route('/receive_content', methods=['POST'])
@login_required
def receive_content_route():
    return receive_content()

@gesture.route('/history')
@login_required
def history():
    records = GestureRecord.query.filter_by(user_id=current_user.id).order_by(GestureRecord.timestamp.desc()).all()
    return render_template('history.html', records=records)

@gesture.route('/gesture_config')
@login_required
def gesture_config():
    # 尝试从缓存获取手势指令内容
    cached_contents = get_cached_gesture_contents()
    if cached_contents:
        return render_template('gesture_config.html', contents=cached_contents)
    return render_template('gesture_config.html', contents=input_contents)

@gesture.route('/update_profile', methods=['POST'])
@login_required
def update_profile():
    try:
        data = request.json
        
        current_user.email = data.get('email')
        current_user.school = data.get('school')
        current_user.department = data.get('department')
        current_user.student_id = data.get('student_id')
        current_user.phone = data.get('phone')
        
        db.session.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': str(e)})

@gesture.route('/upload_video', methods=['POST'])
@login_required
def upload_video_route():
    if 'video' not in request.files:
        return jsonify({'success': False, 'error': '没有上传文件'})
    
    file = request.files['video']
    if file.filename == '':
        return jsonify({'success': False, 'error': '没有选择文件'})
    
    if not allowed_file(file.filename):
        return jsonify({'success': False, 'error': '不支持的文件类型'})
    
    try:
        # 确保上传目录存在
        os.makedirs(UPLOAD_FOLDER, exist_ok=True)
        
        # 生成唯一文件名
        filename = secure_filename(file.filename)
        unique_filename = f"{uuid.uuid4().hex}_{filename}"
        file_path = os.path.join(UPLOAD_FOLDER, unique_filename)
        
        # 保存文件
        file.save(file_path)
        
        # 返回视频URL
        video_url = f"/static/videos/{unique_filename}"
        return jsonify({
            'success': True,
            'video_url': video_url
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}) 